import { login, logout, getInfo } from '@/api/login'

const user = {
  state: {
    hasLogin: false,
    name: '',
    avatar: '',
    roles: [],
    userId:'',
    permissions: []
  },

  mutations: {
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_HASLOGIN: (state, hasLogin) => {
      state.hasLogin = hasLogin;
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId;
    }
  },

  actions: {
    // 登录
    Login({ commit }, loginInfo) {
      const username = loginInfo.username.trim();
      const password = loginInfo.password;
      const type = loginInfo.type;
      const that = this;
      return new Promise((resolve, reject) => {
        login(username, password, type).then(res => {
          // that.dispatch('GetInfo');
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }, query) {
      const that = this;
      return new Promise((resolve, reject) => {
        getInfo(false, query).then(res => {
          // 判断是否为client登录
          if (res.data.redirect && res.data.redirect !== '') {
            location.href = res.data.redirect;
            return;
          }
          that.dispatch('StoreUserInfo', res).then(() => {
            resolve(res);
          }).catch(err => {
            console.log(err);
          })
        }).catch(error => {
          reject(error);
        })
      })
    },

    StoreUserInfo({commit}, res) {
      const that = this;
      const data = res.data;
      return new Promise((resolve, reject) => {
        const user = data.user;
        const avatar = (!user.avatar || user.avatar == "") ? require("@/assets/image/profile.jpg") : user.avatar;
        commit('SET_PERMISSIONS', data.permissions);
        commit('SET_NAME', user.userName);
        commit('SET_AVATAR', avatar);
        commit('SET_HASLOGIN', true);
        commit('SET_USER_ID', user.userId);
        that.dispatch("GenerateRoutes", data.routers)
        .then(accessedRoutes => {
          resolve(accessedRoutes);
        }).catch(err => {console.log(err);reject(err)});
      });

    },

    // 退出系统
    LogOut({ commit }, query) {
      return new Promise((resolve, reject) => {
        logout(query).then(res => {
          commit('SET_PERMISSIONS', []);
          commit('SET_HASLOGIN', false);
          resolve(res);
        }).catch(error => {
          console.error(error)
          reject(error)
        })
      })
    },

    // 前端 登出
    // FedLogOut({ commit }) {
    //   return new Promise(resolve => {
    //     commit()
    //     resolve()
    //   })
    // }
  }
}

export default user
